package com.wx.adapter.api;

import com.alibaba.fastjson2.JSON;
import com.wx.adapter.api.domain.req.MaGetPhoneOldLibVersionReq;
import com.wx.adapter.api.domain.req.MaGetPhoneReq;
import com.wx.adapter.api.domain.req.MaSubscribeMessageReq;
import com.wx.adapter.http.wx.ma.domain.dto.MaSubscribeSendResultDTO;
import com.wx.adapter.http.wx.ma.domain.dto.PhoneInfo;
import com.wx.adapter.http.wx.ma.domain.dto.SnsJsCode2sessionDTO;
import com.wx.adapter.http.wx.ma.service.MiniProgramService;
import com.wx.business.ma.service.MaUserService;
import com.wx.infrastructure.domain.dto.ResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * wx_back_end
 *
 * @Auther: cheng.tang
 * @Date: 2023/2/28 9:58 PM
 * @Description:
 */
@RestController
@Slf4j
public class MiniAppUserController {

    @Autowired
    private MaUserService maUserService;

    @Autowired
    private MiniProgramService miniProgramService;


    @GetMapping("/v1/ma/users/openId")
    public ResultDTO<SnsJsCode2sessionDTO> getOpenId(@RequestParam("wxLoginJSCode") String wxLoginJSCode) {
        log.info("wxLoginJSCode {}", wxLoginJSCode);
        SnsJsCode2sessionDTO snsJsCode2sessionDTO = miniProgramService.snsJscode2session(wxLoginJSCode);
        return ResultDTO.ok(snsJsCode2sessionDTO);
    }

    /**
     * 获取小程序当前用户的手机号
     *
     * @param req
     * @return
     */
    @PostMapping("/v1/ma/users/phones/old")
    public ResultDTO<PhoneInfo> snsJscode2session(@Validated @RequestBody MaGetPhoneOldLibVersionReq req) {
        SnsJsCode2sessionDTO snsJsCode2sessionDTO = miniProgramService.snsJscode2session(req.getWxLoginJSCode());
        PhoneInfo phoneInfo = maUserService.decryptPhone(snsJsCode2sessionDTO.getSessionKey(), req.getEncryptedData(), req.getIv());
        return ResultDTO.ok(phoneInfo);
    }

    /**
     * 获取小程序当前用户的手机号
     *
     * @param req
     * @return
     */
    @PostMapping("/v2/ma/users/phones/new")
    public ResultDTO<PhoneInfo> getPhone(@RequestBody MaGetPhoneReq req) {
        log.info("{}", JSON.toJSONString(req));
        PhoneInfo phone = maUserService.getPhone(req);
        return ResultDTO.ok(phone);
    }


    @PostMapping("/v1/ma/messages/subscribe")
    public ResultDTO<MaSubscribeSendResultDTO> sendSubscribeMessage(@Validated @RequestBody MaSubscribeMessageReq req) {
        return ResultDTO.ok(maUserService.sendSubscribeMessage(req));
    }


}
